package cn.tedu.sp11.filter;

import cn.tedu.web.util.JsonResult;
import com.netflix.zuul.ZuulFilter;
import com.netflix.zuul.context.RequestContext;
import com.netflix.zuul.exception.ZuulException;
import org.apache.commons.lang3.StringUtils;
import org.springframework.cloud.netflix.zuul.filters.support.FilterConstants;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;

@Component
public class AccessFilter extends ZuulFilter {
  /*
  设置过滤器的类型: pre,routing,post, error
   */

    @Override
    public String filterType() {
        //return "pre";
        return FilterConstants.PRE_TYPE;
    }

    @Override
    public int filterOrder() {
        return 6;
    }
/*
   判断针对当前请求,是否要执行过滤代码
   如果用户调用商品,执行过滤代码检查权限

 */

    @Override
    public boolean shouldFilter() {
    /*
        1.获取用户调用的后台服务id
        2.如果服务id 是"item-service"返回true,否则返回false
     */

        RequestContext ctx=RequestContext.getCurrentContext();//从ThreadLocal 获取上下文对象
      String serviceId= (String) ctx.get(FilterConstants.SERVICE_ID_KEY);
        return  "item-service".equalsIgnoreCase(serviceId);
    }

    @Override
    public Object run() throws ZuulException {
       //http://localhost:3001/item-service/6y45634?token=245234243
        /*
            1.接收 token参数
            2.如果没有token, 阻止继续调用, 直接返回登录提示
         */
        //得到上下文对象,再从上下文得到 request对象
        RequestContext ctx=RequestContext.getCurrentContext();
        HttpServletRequest request=ctx.getRequest();
        String token=request.getParameter("token");
       if(StringUtils.isBlank(token)){
           //阻止继续调用后台服务
        ctx.setSendZuulResponse(false);
        //直接向客户端返回响应
           ctx.setResponseStatusCode(401);
           ctx.addZuulResponseHeader("Content-Typpe", "application/jsobn;charset=UTF-8");
           ctx.setResponseBody(JsonResult.err().code(401).msg("not login! 未登录").toString());
       }
        return null;//这个返回值目前没有任何作用,可能会在未来版本中发挥作用
    }
}
